using Sage.Http.Authentication;
using Sage.Http.Models;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;

namespace Sage.Http.Extensions
{
    /// <summary>
    /// 提供HttpClient和HttpRequestMessage的认证相关扩展方法
    /// </summary>
    [Obsolete("此类已过时，请使用HttpExtensions类中的认证方法")]
    public static class HttpClientAuthExtensions
    {
        /// <summary>
        /// 为HttpClient添加Bearer Token认证头
        /// </summary>
        /// <param name="client">HTTP客户端</param>
        /// <param name="token">认证令牌</param>
        /// <param name="scheme">认证方案，默认为"Bearer"</param>
        /// <returns>配置了认证的HTTP客户端，用于链式调用</returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="client"/> 或 <paramref name="token"/> 为null时抛出
        /// </exception>
        [Obsolete("此方法已过时，请使用HttpExtensions.SetBearerToken方法")]
        public static HttpClient AddBearerToken(this HttpClient client, string token, string scheme = "Bearer")
        {
            return HttpExtensions.SetBearerToken(client, token, scheme);
        }

        /// <summary>
        /// 为HttpClient设置默认认证提供者
        /// </summary>
        /// <param name="client">HTTP客户端</param>
        /// <param name="authProvider">认证提供者</param>
        /// <returns>配置了认证的HTTP客户端，用于链式调用</returns>
        [Obsolete("此方法已过时，请使用HttpExtensions.SetDefaultAuthentication方法")]
        public static HttpClient SetDefaultAuthentication(this HttpClient client, IAuthenticationProvider authProvider)
        {
            ArgumentNullException.ThrowIfNull(client);
            ArgumentNullException.ThrowIfNull(authProvider);

            // 使用HttpExtensions中的SetAuthProviderProperty方法
            return HttpExtensions.SetAuthProviderProperty(client, "DefaultAuthProvider", authProvider);
        }

        /// <summary>
        /// 为HttpClient设置Bearer Token认证
        /// </summary>
        /// <param name="client">HTTP客户端</param>
        /// <param name="token">认证令牌</param>
        /// <param name="scheme">认证方案，默认为"Bearer"</param>
        /// <returns>配置了认证的HTTP客户端，用于链式调用</returns>
        [Obsolete("此方法已过时，请使用HttpExtensions.SetBearerToken方法")]
        public static HttpClient SetBearerToken(this HttpClient client, string token, string scheme = "Bearer")
        {
            ArgumentNullException.ThrowIfNull(client);
            ArgumentException.ThrowIfNullOrEmpty(token);

            return SetDefaultAuthentication(client, new BearerTokenAuthProvider(token, scheme));
        }

        /// <summary>
        /// 为HttpClient设置Basic认证
        /// </summary>
        /// <param name="client">HTTP客户端</param>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        /// <returns>配置了认证的HTTP客户端，用于链式调用</returns>
        [Obsolete("此方法已过时，请使用HttpExtensions.SetBasicAuth方法")]
        public static HttpClient SetBasicAuth(this HttpClient client, string username, string password)
        {
            ArgumentNullException.ThrowIfNull(client);
            ArgumentException.ThrowIfNullOrEmpty(username);
            ArgumentException.ThrowIfNullOrEmpty(password);

            return SetDefaultAuthentication(client, new BasicAuthProvider(username, password));
        }

        /// <summary>
        /// 为HttpClient设置API Key认证
        /// </summary>
        /// <param name="client">HTTP客户端</param>
        /// <param name="apiKey">API密钥</param>
        /// <param name="parameterName">参数名称</param>
        /// <param name="location">密钥位置，头部或查询参数</param>
        /// <returns>配置了API Key的HTTP客户端，用于链式调用</returns>
        [Obsolete("此方法已过时，请使用HttpExtensions.SetApiKey方法")]
        public static HttpClient SetApiKey(this HttpClient client, string apiKey, string parameterName, ApiKeyLocation location = ApiKeyLocation.Header)
        {
            ArgumentNullException.ThrowIfNull(client);
            ArgumentException.ThrowIfNullOrEmpty(apiKey);
            ArgumentException.ThrowIfNullOrEmpty(parameterName);

            return SetDefaultAuthentication(client, new ApiKeyAuthProvider(apiKey, parameterName, 
                location == ApiKeyLocation.QueryParameter ? parameterName : null));
        }

        /// <summary>
        /// 为HttpClient添加Basic认证头
        /// </summary>
        /// <param name="client">HTTP客户端</param>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        /// <returns>配置了认证的HTTP客户端，用于链式调用</returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="client"/>, <paramref name="username"/> 或 <paramref name="password"/> 为null时抛出
        /// </exception>
        [Obsolete("此方法已过时，请使用HttpExtensions.SetBasicAuth方法")]
        public static HttpClient AddBasicAuth(this HttpClient client, string username, string password)
        {
            return HttpExtensions.SetBasicAuth(client, username, password);
        }

        /// <summary>
        /// 为HttpClient添加API Key认证（通过默认请求头或默认查询参数）
        /// </summary>
        /// <param name="client">HTTP客户端</param>
        /// <param name="apiKey">API密钥</param>
        /// <param name="parameterName">参数名称</param>
        /// <param name="location">密钥位置，头部或查询参数</param>
        /// <returns>配置了API Key的HTTP客户端，用于链式调用</returns>
        /// <exception cref="ArgumentNullException">参数为null时抛出</exception>
        /// <remarks>
        /// 当位置为QueryParameter时，会将API Key添加到每个请求的查询字符串中，
        /// 这需要在构造URI时处理。建议在可能的情况下使用Header方式。
        /// </remarks>
        [Obsolete("此方法已过时，请使用HttpExtensions.SetApiKey方法")]
        public static HttpClient AddApiKey(this HttpClient client, string apiKey, string parameterName, ApiKeyLocation location = ApiKeyLocation.Header)
        {
            return HttpExtensions.SetApiKey(client, apiKey, parameterName, location);
        }

        /// <summary>
        /// 为单个HTTP请求添加Bearer Token认证
        /// </summary>
        /// <param name="request">HTTP请求消息</param>
        /// <param name="token">认证令牌</param>
        /// <param name="scheme">认证方案，默认为"Bearer"</param>
        /// <returns>配置了认证的HTTP请求，用于链式调用</returns>
        [Obsolete("此方法已过时，请使用BearerTokenAuthProvider类")]
        public static HttpRequestMessage AddBearerToken(this HttpRequestMessage request, string token, string scheme = "Bearer")
        {
            ArgumentNullException.ThrowIfNull(request);
            ArgumentNullException.ThrowIfNull(token);

            request.Headers.Authorization = new AuthenticationHeaderValue(scheme, token);
            return request;
        }

        /// <summary>
        /// 为单个HTTP请求添加Basic认证
        /// </summary>
        /// <param name="request">HTTP请求消息</param>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        /// <returns>配置了认证的HTTP请求，用于链式调用</returns>
        [Obsolete("此方法已过时，请使用BasicAuthProvider类")]
        public static HttpRequestMessage AddBasicAuth(this HttpRequestMessage request, string username, string password)
        {
            ArgumentNullException.ThrowIfNull(request);
            ArgumentNullException.ThrowIfNull(username);
            ArgumentNullException.ThrowIfNull(password);

            var credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{username}:{password}"));
            request.Headers.Authorization = new AuthenticationHeaderValue("Basic", credentials);
            return request;
        }

        /// <summary>
        /// 为单个HTTP请求添加API Key认证
        /// </summary>
        /// <param name="request">HTTP请求消息</param>
        /// <param name="apiKey">API密钥</param>
        /// <param name="parameterName">参数名称</param>
        /// <param name="location">密钥位置，头部或查询参数</param>
        /// <returns>配置了API Key的HTTP请求，用于链式调用</returns>
        [Obsolete("此方法已过时，请使用ApiKeyAuthProvider类")]
        public static HttpRequestMessage AddApiKey(this HttpRequestMessage request, string apiKey, string parameterName, ApiKeyLocation location = ApiKeyLocation.Header)
        {
            ArgumentNullException.ThrowIfNull(request);
            ArgumentNullException.ThrowIfNull(apiKey);
            ArgumentNullException.ThrowIfNull(parameterName);

            if (location == ApiKeyLocation.Header)
            {
                request.Headers.Add(parameterName, apiKey);
            }
            else if (request.RequestUri != null)
            {
                var uriBuilder = new UriBuilder(request.RequestUri);
                var query = System.Web.HttpUtility.ParseQueryString(uriBuilder.Query);
                query[parameterName] = apiKey;
                uriBuilder.Query = query.ToString();
                request.RequestUri = uriBuilder.Uri;
            }

            return request;
        }

        /// <summary>
        /// 设置客户端属性
        /// </summary>
        /// <param name="client">HTTP客户端</param>
        /// <param name="key">属性键</param>
        /// <param name="value">属性值</param>
        /// <returns>HTTP客户端，用于链式调用</returns>
        [Obsolete("此方法已过时，请使用HttpExtensions.SetClientProperty方法")]
        public static HttpClient SetClientProperty(this HttpClient client, string key, object value)
        {
            // 如果是认证提供者，使用专用方法
            if (value is IAuthenticationProvider authProvider)
            {
                return HttpExtensions.SetAuthProviderProperty(client, key, authProvider);
            }
            
            // 否则直接返回客户端，因为无法在AOT环境中序列化通用对象
            return client;
        }

        /// <summary>
        /// 获取客户端属性
        /// </summary>
        /// <typeparam name="T">属性类型</typeparam>
        /// <param name="client">HTTP客户端</param>
        /// <param name="key">属性键</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>属性值，如果不存在则返回默认值</returns>
        [Obsolete("此方法已过时，请使用HttpExtensions.GetClientProperty方法")]
        public static T? GetClientProperty<T>(this HttpClient client, string key, T? defaultValue = default)
        {
            return HttpExtensions.GetClientProperty<T>(client, key, null, defaultValue);
        }
    }
}
